package cn.huijielong.modules.group.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

import cn.huijielong.modules.group.dao.GoodsDao;
import cn.huijielong.modules.group.entity.GoodsEntity;
import cn.huijielong.modules.group.entity.GroupEntity;
import cn.huijielong.modules.group.service.GoodsService;
import cn.huijielong.modules.oss.entity.Base64File;
import cn.huijielong.modules.oss.entity.OssFileEntity;
import cn.huijielong.modules.oss.service.OssFileService;
import cn.huijielong.modules.sys.service.impl.SimpleServiceImpl;
import cn.huijielong.common.utils.Query;
import cn.huijielong.common.validator.ValidatorUtils;
import cn.huijielong.common.validator.group.Group;



@Service("goodsService")
public class GoodsServiceImpl extends SimpleServiceImpl implements GoodsService {
	@Autowired
	private GoodsDao goodsDao;
	@Autowired
	private OssFileService ossFileService;
	
	@Override
	public GoodsEntity queryObject(Long goodsId){
		return goodsDao.queryObject(goodsId);
	}
	
	@Override
	public Page<GoodsEntity> queryList(Query q){
	    Page<GoodsEntity> page=PageHelper.startPage(q.getPage(), q.getLimit()).doSelectPage(()-> goodsDao.queryList(q));
		return page;		
	}
	
	@Override
	public int queryTotal(Map<String, Object> map){
		return goodsDao.queryTotal(map);
	}
	
	@Transactional
	@Override
	public void save(GoodsEntity goods){
		ValidatorUtils.validateEntity(goods, Group.class);
		goodsDao.save(goods);
	}
	
	@Override
	public void update(GoodsEntity goods){
		
		goodsDao.update(goods);
	}
	@Transactional
	@Override
	public void uploadImage(List<MultipartFile> img,Long goodsId,boolean add){
		OssFileEntity ossGoods=new OssFileEntity();
		ossGoods.setTableId(goodsId);
		ossGoods.setStoreType(OssFileEntity.STORE_TYPE_0);
		ossGoods.setTableType(OssFileEntity.TABLE_TYPE_4);
		ossGoods.setStatus("0");
		ossGoods.setUploadFile(img);
		if(add) {
			ossFileService.save(ossGoods);
		}else {
			ossFileService.update(ossGoods);
		}
		
		GoodsEntity goods=new GoodsEntity();
		goods.setGoodsId(goodsId);
		goods.setHeadImg(ossGoods.getFirstUrl());
		goodsDao.updateHeadImg(goods);
	}
	@Override
	public void delete(Long goodsId){
		goodsDao.delete(goodsId);
	}
	
	@Override
	public void deleteBatch(Long[] goodsIds){
		goodsDao.deleteBatch(goodsIds);
	}

	@Override
	public void save(List<GoodsEntity> goodsList) {
		goodsList.forEach(g->{
			save(g);
		});
	}

	@Override
	public void update(List<GoodsEntity> goodsList) {
		goodsList.forEach(g->{
			if(g.getGoodsId()==null)
				save(g);
			else
				update(g);
		});
	}
	
}
